package com.gc.repository.impl;

import com.gc.entity.Course;
import com.gc.repository.CourseRepository;
import com.gc.util.C3p0Utils;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;

import java.sql.SQLException;
import java.util.List;

public class CourseRepositoryImpl implements CourseRepository {
    @Override
    public boolean Add(Course course) {
        QueryRunner qr = new QueryRunner(C3p0Utils.getDataSource());
        try {
            qr.update("insert into course(name, cid) VALUES (?, ?) ",
                    course.getName(),
                    course.getCid()
            );
            return true;
        } catch (SQLException e) {
            e.printStackTrace();
            return false;
        }
    }

    @Override
    public List<Course> FindAll() {
        QueryRunner qr = new QueryRunner(C3p0Utils.getDataSource());
        try {
            List<Course> query = qr.query("select * from course", new BeanListHandler<>(Course.class));

            return query;
        } catch (SQLException e) {
            e.printStackTrace();
            return null;
        }
    }

    @Override
    public boolean DelById(Long id) {
        QueryRunner qr = new QueryRunner(C3p0Utils.getDataSource());
        try {
            int res = qr.update("delete from course WHERE id = ?", id);
            System.out.println(res);
            return true;
        } catch (SQLException e) {
            e.printStackTrace();
            return false;
        }
    }

    @Override
    public Course FindById(Long id) {
        QueryRunner qr = new QueryRunner(C3p0Utils.getDataSource());
        try {
            Course res = qr.query("select * from course WHERE id = ?", new BeanHandler<>(Course.class),
                    id);
            System.out.println(res);
            return res;
        } catch (SQLException e) {
            e.printStackTrace();
            return null;
        }
    }

    @Override
    public Course FindByCourseId(String cid) {
        QueryRunner qr = new QueryRunner(C3p0Utils.getDataSource());
        try {
            Course res = qr.query("select * from course WHERE cid = ?", new BeanHandler<>(Course.class),
                    cid);
            System.out.println(res);
            return res;
        } catch (SQLException e) {
            e.printStackTrace();
            return null;
        }
    }

    @Override
    public boolean UpdateById(Course course) {
        QueryRunner qr = new QueryRunner(C3p0Utils.getDataSource());
        try {
            int res = qr.update("update course set name = ?, cid = ? where id = ?",
                    course.getName(),
                    course.getCid(),
                    course.getId());
            return true;
        } catch (SQLException e) {
            e.printStackTrace();
            return false;
        }
    }
}
